#include<func.h>
#define N 20000000
//子线程，主线程，同时对一个变量加2千万，通过加锁，实现最终效果是4千万
typedef struct{
    int num;
    pthread_mutex_t mutex;
}data_t;

void thread_func(void*p)//子线程加两千万
{
    data_t* d=(data_t*)p;
    int i;
    for(i=0;i<N;i++)
    {
        pthread_mutex_lock(&d->mutex);//加锁
        d->num+=1;//子线程加两千万
        pthread_mutex_unlock(&d->mutex);//解锁
    }
}
//主线程和子线程各加1千万
int main()
{
    data_t d;
    d.num=0;
    int ret=pthread_mutex_init(&d.mutex,NULL);//初始化锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_init");
    pthread_t pthid;
    ret=pthread_create(&pthid,NULL,thread_func,(void*)&d);//创建子线程
    THREAD_ERR_CHECK(ret,"pthread_create");
    int i;
    for(i=0;i<N;i++)
    {
        pthread_mutex_lock(&d.mutex);//加锁
        d.num+=1;//主线程加两千万
        pthread_mutex_unlock(&d.mutex);//解锁
    }
    ret=pthread_join(pthid,NULL);//等待子线程
    THREAD_ERR_CHECK(ret,"pthread_join")
    ret=pthread_mutex_destroy(&d.mutex);//销毁锁
    THREAD_ERR_CHECK(ret,"pthread_mutex_destroy");
    printf("num=%d\n",d.num);//打印最终结果
    return 0;
}
